建立專案,加入→現有專案,將BindingLibrary加入專案
相依性→新增專案供參考,BindingLibrary打勾
新增ViewModels資料夾,加入類別MainViewModel
先using BindingLibrary,class前面加internal後繼承NotifyPropertyBase
using BindingLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample.ViewModels
{
internal class MainViewModel : NotifyPropertyBase
{
private float _number=0;
public float Number
{
get { return _number; }
set { SetProperty(ref _number, value); }
}
}
}
<Window x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Sample"
xmlns:vm="clr-namespace:Sample.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox Width="100" Text="{Binding Number, Mode=OneWayToSource ,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Width="100" Text="{Binding Number}"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;
namespace Sample.Converters
{
internal class ValueColorConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var v = (float)value;
if (v > 100.5) return new SolidColorBrush(Colors.GreenYellow);
else return new SolidColorBrush(Colors.Red);
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox Width="100" Text="{Binding Number, Mode=OneWayToSource ,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Width="100" Text="{Binding Number}" Foreground="{Binding Number, Converter={StaticResource NumberColorConverter}}"/>
</StackPanel>